package com.rockcent.mall;

import com.alibaba.fastjson.JSON;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.utils.RequestUtils;
import com.rockcent.mall.helper.UserHelper;
import com.rockcent.mall.lib.domain.UserInfo;
import com.rockcent.mall.lib.dto.UserInfoDto;
import com.rockcent.mall.lib.repository.UserInfoRepository;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by oyhk on 15/11/29.
 * 自动登录过滤器
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

    private final Logger log = LoggerFactory.getLogger(AuthInterceptor.class);

    @Autowired
    private UserHelper userHelper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserInfoRepository userInfoRepository;

    private String userToken;


    public AuthInterceptor(String userToken) {
        this.userToken = userToken;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        response.setContentType("application/json");
        UserInfoDto userBase = userHelper.getSession(request);
        if (userBase != null) {
            return true;
        }


        log.info("======================>this.userToken : {}", this.userToken);

        String userToken = request.getHeader(this.userToken);

        if (StringUtils.isBlank(userToken)) {
            userToken = RequestUtils.getStringParameter(request, this.userToken);
        }

        log.info("======================>userToken : {}", userToken);
        if (StringUtils.isBlank(userToken)) {
            response.getWriter().print(JSON.toJSONString(new JsonResult<>("10001", "user_token 不能为空")));
            response.getWriter().close();
            return false;
        }
        String domain = request.getHeader("domain");
        if (StringUtils.isBlank(domain)) {
            domain = RequestUtils.getStringParameter(request, "domain");
        }

        if (StringUtils.isBlank(domain)) {
            response.getWriter().print(JSON.toJSONString(new JsonResult<>("10002", "domain 不能为空")));
            response.getWriter().close();
            return false;
        }

        String userInfoId = stringRedisTemplate.boundValueOps(UserInfo.REDIS_USER_TOKEN_PREFIX + userToken).get();
        if (StringUtils.isBlank(userInfoId)) {
            response.getWriter().print(JSON.toJSONString(new JsonResult<>("10003", "user_token 无效")));
            response.getWriter().close();
            return false;
        }
        UserInfo userInfo = userInfoRepository.findOne(Long.valueOf(userInfoId));
        if (userInfo == null) {
            response.getWriter().print(JSON.toJSONString(new JsonResult<>("10003", "user_token 无效")));
            response.getWriter().close();
            return false;
        }

        // 设置登录的session
        UserInfoDto userInfoDto = userHelper.setSession(userInfo, request);
        request.getSession().setAttribute(UserInfo.LOGIN_USER, userInfoDto);

        return super.preHandle(request, response, handler);
    }
}
